#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# export config info setup.yaml server_ip, my_email, my_name.

. $CCI_SRC/lib/log.sh

export_config_variables()
{
	[[ -n "$my_email" && -n "$my_name" && -n "$my_account" ]] && return

	options=( server_ip my_name my_email my_account lab)

	for option in ${options[@]}
	do
		export $option=$(awk -F ": " '/^'$option'/ {print $2}' /etc/compass-ci/setup.yaml)
	done
}

check_segment()
{
	server_ip_segment=$(ip route get 1.2.3.4 | awk '{print $7; exit}' | awk -F. '{print $1"."$2}')
	export br0_segment=$(awk '/^br0_segment:\s/ {print $2; exit}' /etc/compass-ci/setup.yaml)

	[ "$server_ip_segment" != "$br0_segment" ] || {
		export br0_segment=172.$(($(date +%s%N)%13+19))
		sed -i "s/br0_segment: 172.18/br0_segment: ${br0_segment}/g" /etc/compass-ci/setup.yaml
	}
}

check_selinux()
{
	selinux=$(getenforce)
	[[ "$selinux" == "Enforcing" ]] && {
		log_error "selinux status is $selinux, please try: setenforce 0, and config /etc/selinux/config(set SELINUX=permissive or SELINUX=disabled)"
		exit 1
	}
}

mkdir -p /etc/compass-ci/
chmod 775 /etc/compass-ci/
cp -a $CCI_SRC/sparrow/setup.yaml /etc/compass-ci/setup.yaml
export_config_variables

[[ -n "$my_email" && -n "$my_name" && -n "$my_account" && -n "$lab" ]] || {
	log_error "A least one of the below variable is empty, please config $CCI_SRC/sparrow/setup.yaml"
	echo -e "my_email=$my_email\nmy_name=$my_name\nmy_account=$my_account\nlab=$lab"
	exit 1
}

check_segment
check_selinux
